<?php

namespace App\Services;

use App\Models\Department;
use Illuminate\Support\Facades\DB;

class DepartmentService
{
    /**
     * 创建部门
     *
     * @param array $data
     * @return Department
     */
    public function create(array $data): Department
    {
        return Department::create([
            'parent_id' => $data['parent_id'] ?? 0,
            'name' => $data['name'],
            'code' => $data['code'] ?? null,
            'leader' => $data['leader'] ?? null,
            'phone' => $data['phone'] ?? null,
            'email' => $data['email'] ?? null,
            'status' => $data['status'],
            'sort' => $data['sort'] ?? 0,
            'remark' => $data['remark'] ?? null,
        ]);
    }

    /**
     * 更新部门
     *
     * @param Department $department
     * @param array $data
     * @return Department
     */
    public function update(Department $department, array $data): Department
    {
        $department->update([
            'parent_id' => $data['parent_id'] ?? 0,
            'name' => $data['name'],
            'code' => $data['code'] ?? null,
            'leader' => $data['leader'] ?? null,
            'phone' => $data['phone'] ?? null,
            'email' => $data['email'] ?? null,
            'status' => $data['status'],
            'sort' => $data['sort'] ?? 0,
            'remark' => $data['remark'] ?? null,
        ]);

        return $department;
    }

    /**
     * 删除部门
     *
     * @param Department $department
     * @return bool
     * @throws \Exception
     */
    public function delete(Department $department): bool
    {
        if (Department::hasChildren($department->id)) {
            throw new \Exception('存在子部门，无法删除');
        }

        if ($department->users()->exists()) {
            throw new \Exception('部门下存在用户，无法删除');
        }

        return $department->delete();
    }

    /**
     * 构建查询
     *
     * @param array $filters
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function buildQuery(array $filters = [])
    {
        $query = Department::with('parent');

        if (isset($filters['name'])) {
            $query->where('name', 'like', '%' . $filters['name'] . '%');
        }

        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        return $query->orderBy('sort')->orderBy('id');
    }
}

